package com.jy.api.controller.admin;

import com.jy.api.controller.admin.params.LeaseProductParams;
import com.jy.api.dao.*;
import com.jy.api.domain.*;
import com.jy.api.service.LeaseProductService;
import com.jy.api.util.MyDateUtils;
import com.jy.api.util.PinYinUtil;
import com.jy.api.util.RedisSyncLocker;
import com.jy.api.util.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xiaohua
 * @data 2024/11/14 0014 18:49
 */
@Slf4j
@RestController
@RequestMapping(value = "v1/admin", produces = "application/json;charset=utf-8")
public class LeaseProductController {

    @Resource
    private LeaseProductService leaseProductService;
    @Resource
    private LeaseProductTypeDao leaseProductTypeDao;
    @Resource
    private LeaseProductDao leaseProductDao;
    @Autowired
    private RedisSyncLocker redisSyncLocker;
    @Resource
    private EmployeeDao employeeDao;
    @Resource
    private LeaseProductTransactionDao leaseProductTransactionDao;
    @Resource
    private BillRuleDao billRuleDao;



    @GetMapping("/lease/transaction/list")
    public ResponseEntity productTransactionList(@RequestParam("storeId") String storeId, @PageableDefault(value = 10, sort = {"addTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        return new ResponseEntity(leaseProductTransactionDao.findByStoreId(storeId, pageable), HttpStatus.OK);
    }
    /**
     * 编辑/移除/添加原料
     *
     * @param params
     * @return
     */
    @PostMapping("/edit/lease")
    public ResponseEntity addMaterial(@RequestBody LeaseProductParams params, Principal principal) throws Exception {
        if (params.getId() > 0) {
            return (ResponseEntity) redisSyncLocker.idLock(params.getId() + "leaseLock", o -> {
                LeaseProduct product = leaseProductService.findOne(params.getId());
                if (product == null) {
                    return new ResponseEntity("商品不存在，请核实后进行添加", HttpStatus.BAD_REQUEST);
                }
                for (LeaseProductExtra extra : params.getExtras()) {
                    BillRule billRule = billRuleDao.findOne(extra.getRuleId());
                    if (billRule==null){
                        return ResponseEntity.badRequest().body("计费规则不存在，请核实后进行添加");
                    }
                    if (extra.getAmount()==0 && billRule.getOneHourAmount()!=0){
                        return ResponseEntity.badRequest().body("计费规则非免费模式，押金不能为0");
                    }
                }
                Employee employees = employeeDao.findByStoreIdAndUsernameAndEnabledIsTrue(product.getStoreId(), principal.getName());
                LeaseProductTransaction transaction = new LeaseProductTransaction();
                transaction.setProductName(product.getName());
                transaction.setStoreId(product.getStoreId());
                transaction.setProductId(product.getId());
                StringBuilder stringBuffer = new StringBuilder();
                stringBuffer.append(employees.getName()).append("在").append(MyDateUtils.dtSimpleFormatHour(new Date())).append("修改了商品\n");
                if (!product.getName().equals(params.getName())){
                    stringBuffer.append("商品名字为:" + "变动前:" + product.getName() + "\n" + "变动后:" + params.getName() + "\n");
                }
                if (product.getTotalCount()!=(params.getTotalCount())){
                    stringBuffer.append("商品库存总量为:" + "变动前:" + product.getTotalCount() + "\n" + "变动后:" + params.getTotalCount() + "\n");
                }
                if (!(product.isBuyEnabled()+"").equals(params.isBuyEnabled()+"")){
                    stringBuffer.append("商品是否允许购买为:" + "变动前:" + product.isBuyEnabled() + "\n" + "变动后:" + params.isBuyEnabled() + "\n");
                }
                if (!(product.isShowPcEnabled()+"").equals(params.isShowPcEnabled()+"")){
                    stringBuffer.append("商品是否展示pc为:" + "变动前:" + product.isShowPcEnabled() + "\n" + "变动后:" + params.isShowPcEnabled() + "\n");
                }
                if (!(product.getImage()+"").equals(params.getImage()+"")){
                    stringBuffer.append("商品图片有变动");
                    transaction.setOriImage(product.getImage());
                    transaction.setNowImage(params.getImage());
                }
                transaction.setNotice(stringBuffer.toString());
                BeanUtils.copyProperties(params, product, "id");
                product.setPinyin(PinYinUtil.getFirstSpell(product.getName()));
                product.setUpdateTime(new Date());
                leaseProductTransactionDao.save(transaction);
                leaseProductService.save(product);
                return ResponseEntity.ok("修改成功");
            });
        } else {
            for (LeaseProductExtra extra : params.getExtras()) {
                BillRule billRule = billRuleDao.findOne(extra.getRuleId());
                if (billRule==null){
                    return ResponseEntity.badRequest().body("计费规则不存在，请核实后进行添加");
                }
                if (extra.getAmount()==0 && billRule.getOneHourAmount()!=0){
                    return ResponseEntity.badRequest().body("计费规则非免费模式，押金不能为0");
                }
            }
            LeaseProduct product = new LeaseProduct();
            BeanUtils.copyProperties(params, product, "id");
            product.setPinyin(PinYinUtil.getFirstSpell(product.getName()));
            product.setUpdateTime(new Date());
            leaseProductService.save(product);
            return ResponseEntity.ok("新建成功");
        }
    }


    /**
     * 编辑/移除/添加原料
     *
     * @param params
     * @return
     */
    @PostMapping("/edit/lease/type")
    public ResponseEntity editLeaseType(@RequestBody LeaseProductParams params) {
        LeaseProductType productType;
        if (params.getId() > 0) {
            productType = leaseProductTypeDao.findOne(params.getId());
            if (productType == null) {
                return new ResponseEntity("商品不存在，请核实后进行添加", HttpStatus.BAD_REQUEST);
            }
        } else {
            productType = new LeaseProductType();
        }
        BeanUtils.copyProperties(params, productType, "id");
        leaseProductTypeDao.save(productType);
        if (params.getId() > 0) {
            leaseProductDao.updateLeaseProduct(productType.getName(), params.getId());
        }
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 编辑/移除/添加原料
     *
     * @param params
     * @return
     */
    @PostMapping("/delete/lease/type")
    public ResponseEntity deleteLeaseType(@RequestBody LeaseProductParams params) {
        leaseProductTypeDao.delete(params.getId());
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 编辑/移除/添加原料
     *
     * @param params
     * @return
     */
    @PostMapping("/delete/lease")
    public ResponseEntity editLease(@RequestBody LeaseProductParams params) {
        leaseProductService.delete(params.getId());
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 编辑/移除/添加原料
     *
     * @param params
     * @return
     */
    @PostMapping("/lease/type/list")
    public ResponseEntity typeList(@RequestBody LeaseProductParams params) {
        List<LeaseProductType> productType = leaseProductTypeDao.findByStoreId(params.getStoreId());
        return ResponseEntity.ok().body(productType);
    }

    /**
     * 编辑/移除/添加原料
     *
     * @param params
     * @return
     */
    @PostMapping("/lease/product/list")
    public ResponseEntity productList(@RequestBody LeaseProductParams params) {
        if (params.getKeyword() == null || "".equals(params.getKeyword().trim())) {
            List<LeaseProduct> result = leaseProductService.findByStoreIdOrderByQueueDesc(params.getStoreId());
            return ResponseEntity.ok(result);
        } else {
            params.getKeyword().trim();
            Specification<LeaseProduct> spec = (root, criteriaQuery, criteriaBuilder) -> {
                List<Predicate> predicates = new ArrayList<>();
                if (ValidatorUtil.isChinese(params.getKeyword())) {
                    predicates.add(criteriaBuilder.like(root.get("name"), "%" + params.getKeyword() + "%"));
                } else {
                    predicates.add(criteriaBuilder.like(root.get("pinyin"), "%" + params.getKeyword() + "%"));
                }
                predicates.add(criteriaBuilder.equal(root.get("storeId"), params.getStoreId()));
                if (params.getProductTypeId() > 0) {
                    predicates.add(criteriaBuilder.equal(root.get("productTypeId"), params.getProductTypeId()));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            };
            List<LeaseProduct> list = leaseProductService.findAll(spec);
            return ResponseEntity.ok().body(list);
        }
    }


}
